package org.mobile.servlets;

import java.io.IOException;
import java.security.NoSuchAlgorithmException;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.mobile.beans.User;
import org.mobile.encryption.MD5;
import org.mobile.logic.UserLogic;

/**
 * Servlet implementation class ChangePass
 */
@WebServlet(name = "changePass", urlPatterns = { "/changePass" })
public class ChangePass extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public ChangePass() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		int userID= Integer.parseInt(request.getParameter("userID"));
		String password= request.getParameter("new_password");
		String oldPassword= request.getParameter("old_password");
		User user= UserLogic.getInstance().getUser(userID);
		try {
			if(user.getPassword().equals(MD5.encrypt(oldPassword))){
				if(UserLogic.getInstance().changePassword(password, userID)){
					request.setAttribute("message", "Hasło zostało zmienione");
					request.getRequestDispatcher("index.jsp").forward(request, response);
					
				}
				else{
					request.setAttribute("error", "Błąd zmiany hasła!");
					request.getRequestDispatcher("errPage.jsp").forward(request, response);
				}
			}
			else{
				request.setAttribute("error", "Złe hasło!");
				request.getRequestDispatcher("errPage.jsp").forward(request, response);
			}
		} catch (NoSuchAlgorithmException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

}
